package com.study.domain;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import org.springframework.messaging.Message;

import java.sql.Timestamp;

@Data
public class TMqttMsg {


    /**消息接收时间*/
   private Timestamp ts;

    /**消息id*/
   private String msgid;

   /**消息主题*/
   private String mqtt_topic;
   /**消息类别*/
   private  Integer qos;
    /**消息*/
   private  String payload;
     /**客户端id*/
   private String clientid;

   private Timestamp arrived;


    /**

     {
     "mqtt_receivedRetained": true,
     "mqtt_id": 0,
     "mqtt_duplicate": false,
     "id": "5c396b63-5fb0-576f-4d9a-2b0506d81c29",
     "mqtt_receivedTopic": "/yy",
     "mqtt_receivedQos": 0,
     "timestamp": 1735614974371
     }

     */
   public static TMqttMsg covert(Message<String> message) {
        //转换成json
       JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(message.getHeaders()));

       TMqttMsg msg = new TMqttMsg();
       msg.setMsgid(jsonObject.getString("id"));
       msg.setTs(new Timestamp(jsonObject.getLong("timestamp")));
       msg.setQos(jsonObject.getInteger("mqtt_receivedQos"));
       //放入mqtt消息
       msg.setPayload(message.getPayload());

       String mqttReceivedTopic = jsonObject.getString("mqtt_receivedTopic");
       //放入主题
       msg.setMqtt_topic(mqttReceivedTopic);
       //放入客户端id
       msg.setClientid(extractClientIdFromTopic(mqttReceivedTopic));
       msg.setArrived(new Timestamp(System.currentTimeMillis()));
       return msg;

   }


    private static String extractClientIdFromTopic(String topic) {
        // 假设主题结构为 "devices/{clientId}/data"
        String[] parts = topic.split("/");
        if (parts.length > 2) {
            return parts[2]; // clientId
        }
        return null;
    }

}
